<?php


namespace app\controllers;

use app\models\Users;
use Slim;
use slimExt\base\Request;
use slimExt\base\Response;

/**
 * Class SimpleAuth
 * @package app\controllers
 */
class SimpleAuth extends Base
{
    protected $tplPathPrefix = 'mder';

    /**
     * login
     * @api /_mder/login
     *
     * @param Request $req
     * @param Response $res
     * @return int|mixed
     */
    public function loginAction()
    {
        if ( $this->request->isPost() ) {
            return $this->doLogin();
        }

        if ( Slim::get('user')->isLogin() ) {
            return redirect_to( Slim::config()->get('urls.afterLoginTo', '/') );
        }

        // $oldInputs = $req->getOldInput();
        // $user = new Users($req->getOldInput());
        // de($user, $user['username']);

        return $this->renderTwig('login', [
            'user' => $this->request->getOldInput()
        ]);
    }

    /**
     * @param Request $req
     * @param Response $res
     * @return int|mixed
     */
    protected function doLogin()
    {
        // $body = $req->getParsedBody();
        $req = $this->request;
        $username = $req->get('username', 'string');
        $password = $req->get('password', 'string');

        $redirect = Slim::config()->get('urls.afterLoginTo' , '/');

        if ( Slim::get('user')->isLogin() ) {
            return redirect_to( $redirect );
        }

        // check
        $user = new Users();
        $result = $user->login($username, $password);
        $msg    = 'login successful!!';
        $type   = 'success';
        $data = ['redirect' => $redirect];

        if ( is_string($result) ) {
            $msg  = $result;
            $type = 'warning';
            $data = [];
            $redirect = Slim::config()->get('urls.login');
        }

        if ( $req->isXhr() ) {
            return $this->response->withJson( $data, 0, $msg );
        }

        // page alert message
        // alert_messages(['type' => $type, 'msg' => $msg]);
        // return $this->response->withRedirect($redirect);

        return $this->response ->withRedirect($redirect)
                    ->withMessage([
                        'type' => $type,
                        'msg'  => $msg
                    ])
                    ->withInput([
                        'username' => $username,
                        'password' => $password,
                    ]);
    }

    public function logoutAction()
    {
        Slim::get('user')->logout();

        return redirect_to( Slim::config()->get('urls.afterLogoutTo', '/') );
    }
}